﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Media;
using ICSharpCode.AvalonEdit;
using Peter.Common.Controls;

namespace Peter.Logic.AvalonEdit
{
   /// <summary>
   /// Service used to mark all occurances of the find text.
   /// </summary>
   public class FindTextMarkerService : TextMarkerService
   {
      private readonly InsightHighlight m_Highlight;

      /// <summary>
      /// Initializes the find text marker service.
      /// </summary>
      /// <param name="editor">The text editor to attach to.</param>
      /// <param name="highlight"></param>
      public FindTextMarkerService (TextEditor editor, InsightHighlight highlight)
         : base (editor)
      {
         this.m_Highlight = highlight;
      }

      /// <summary>
      /// Marks all occurances of the find text.
      /// </summary>
      /// <param name="searchText">Text to mark.</param>
      /// <param name="ignoreCase">True to ignore case, otherwise false.</param>
      /// <param name="isRegex">True if search with regular expressions.</param>
      /// <returns>The number of items highlighted.</returns>
      public int MarkFindText (string searchText, bool ignoreCase, bool isRegex)
      {
         int count = 0;
         this.RemoveAll ();
         this.m_Highlight.Lines.Clear ();
         if (!string.IsNullOrEmpty (searchText)) {
            try {
               var matches = Regex.Matches (this.Editor.Text, isRegex ? searchText : Regex.Escape (searchText),
                                             ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
               foreach (Match match in matches) {
                  this.Create (match.Index, match.Length).BackgroundColor = Colors.Bisque;
                  var location = this.Editor.Document.GetLocation (match.Index);
                  this.m_Highlight.Lines.Add (new InsightLine (location.Line, location.Column));
               }
               count = matches.Count;
               if (count > 0) {
                  var location = this.Editor.Document.GetLocation (matches [0].Index);
                  this.Editor.ScrollTo (location.Line, location.Column);
               }
            } catch (Exception) {
               return 0;
            }
         }
         this.m_Highlight.Redraw ();
         return count;
      }
   }
}
